<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="订单号" prop="workOrderNo">
                <el-input v-model="queryParams.workOrderNo" placeholder="请输入订单号" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="物料编号" prop="materialCode">
                <el-input v-model="queryParams.materialCode" placeholder="请输入物料编号" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="物料名称" prop="materialName">
                <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="生产状态" prop="taskPlanStatus">
                <el-select v-model="queryParams.taskPlanStatus" placeholder="请选择">
                    <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="计划开始日期">
                <el-date-picker v-model="dateRange" style="width: 340px" value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetimerange" range-separator="-" start-placeholder="开始日期"
                    end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleImport"
                    v-hasPermi="['business:productionPlan:import']">计划导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleDownload"
                    v-hasPermi="['business:productionPlan:import']">下载模板</el-button>
            </el-col>
            <el-col :span="1.5">
              <!-- v-hasPermi="['business:productionPlan:add']" -->
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   >新增</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="planList">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column label="序号" type="index" width="50">
            </el-table-column>
            <el-table-column label="工单号" prop="workOrderNo" width="auto" />
            <el-table-column label="任务号" prop="taskNo" width="auto" />
            <el-table-column label="工程号" prop="projectCode" width="auto" />
            <el-table-column label="工程名称" prop="projectName" width="auto" />
            <el-table-column label="物料编号" prop="materialCode" :show-overflow-tooltip="true" width="auto" />
            <el-table-column label="物料名称" prop="materialName" :show-overflow-tooltip="true" width="auto" />
            <el-table-column label="计划数量" prop="dispatchQty" :show-overflow-tooltip="true" width="auto" />
            <el-table-column label="已完成数量" prop="completedQty" :show-overflow-tooltip="true" width="auto" />
            <el-table-column label="计划开始日期" prop="planStartTime" :show-overflow-tooltip="true" width="auto">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.planStartTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="计划结束日期" prop="planEndTime" :show-overflow-tooltip="true" width="auto">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.planEndTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="实际开始时间" prop="taskStartTime" :show-overflow-tooltip="true" width="auto">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.taskStartTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="实际结束时间" prop="taskEndTime" :show-overflow-tooltip="true" width="auto">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.taskEndTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="生产状态" prop="taskPlanStatus" :show-overflow-tooltip="true" width="auto">
                <template slot-scope="scope">
                    {{ scope.row.taskPlanStatus == 0 ?'未开始':(scope.row.taskPlanStatus == 1
                    ?'生产中':(scope.row.taskPlanStatus == 2 ?'已完成':'暂停'))}}
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" v-if="scope.row.taskPlanStatus == 0"
                        @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="text" :disabled="scope.row.taskPlanStatus != 0"
                        @click="handleIssued(scope.row,1)">下发</el-button>

                    <el-button size="mini" type="text" v-if="scope.row.taskPlanStatus == 1"
                        @click="handleIssued(scope.row,3)">暂停</el-button>

                    <el-button size="mini" type="text" v-if="scope.row.taskPlanStatus == 3"
                        @click="handleIssued(scope.row,4)">恢复</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :before-upload="onBeforeUpload" name="file" :action="upload.url" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <!-- <div class="el-upload__tip" slot="tip">
                        <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                    </div> -->
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <!-- <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                        @click="importTemplate">下载模板</el-link> -->
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

            <!-- 新增编辑 -->
            <formDialog ref="formDialogRef" @ok="reloadTable()"></formDialog>
    </div>
</template>

<script>
    import { downloadTemplate, getList, taskDeliver } from "@/api/lineProduction/index";
import { getToken } from "@/utils/auth";
import { downloadXls } from '@/utils/ruoyi';
import formDialog from './formDialog.vue';

    export default {
        name: "Role",
        components:{
          formDialog
        },
        data() {
            return {
                // 遮罩层
                loading: false,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 计划表格数据
                planList: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 日期范围
                dateRange: ['', ''],
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10
                },
                // 生产状态
                stateOptions: [
                    {
                        label: '未开始',
                        value: 0
                    },
                    {
                        label: '生产中',
                        value: 1
                    },
                    {
                        label: '已完成',
                        value: 2
                    },
                    {
                        label: '暂停',
                        value: 3
                    }
                ],
                // 用户导入参数
                upload: {
                    // 是否显示弹出层（用户导入）
                    open: false,
                    // 弹出层标题（用户导入）
                    title: "",
                    // 是否禁用上传
                    isUploading: false,
                    // 设置上传的请求头部
                    headers: { Authorization: "Bearer " + getToken() },
                    // 上传的地址
                    url: process.env.VUE_APP_BASE_API + "/productionPlan/importData"
                },
            };
        },
        created() {
            this.getList()
        },
        methods: {
            /** 搜索按钮操作 */
            handleQuery() {
                // this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.dateRange = [];
                this.resetForm("queryForm");
                // this.queryParams = undefined;
                this.handleQuery();
            },
            getList() {
                getList({ ...this.queryParams, planStartTime: this.dateRange[0], planEndTime: this.dateRange[1] }).then(res => {
                    this.planList = res.rows
                    this.total = res.total
                })
            },
            // 任务下发
            handleIssued(row, status) {
              this.loading = true
                let params = {
                    id: row.id,
                    taskNo: row.taskNo,
                    taskPlanStatus: status
                }
                if(status==1){
                  params.distributionStatus=0
                }
                taskDeliver(params).then(res => {
                    if(res.msg=='未调用成功mes接口'&&status==1){
                      this.$confirm('mes连接失败，请先确认物料是否充足！', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                      }).then(() => {
                        let datat_ = {
                          taskNo: row.taskNo,
                          taskPlanStatus: status,
                          distributionStatus:1
                        }
                        taskDeliver(datat_).then(res => {
                          this.$message.success(res.msg)
                          this.getList()
                          this.loading = false
                        })

                      }).catch(() => {
                        this.loading = false
                        this.getList()
                      });
                    }else{
                      this.loading = false
                      this.$message.success(res.msg)
                      this.getList()
                    }
                }).catch(err=>{
                  this.loading = false
                })
            },
            handleDownload() {
                downloadTemplate().then(res => {
                    downloadXls(res, '生产计划.xlsx')
                }).catch(error => {
                    this.$message.error("下载模版出错")
                })
            },
            handleImport() {
                this.upload.title = "计划导入";
                this.upload.open = true;
            },
            // 文件上传中处理
            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true;
            },
            // 文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                this.upload.open = false;
                this.upload.isUploading = false;
                this.$refs.upload.clearFiles();
                this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
                this.getList();
            },
            // 提交上传文件
            submitFileForm() {
                this.$refs.upload.submit();
            },
            onBeforeUpload(file) {
                console.log(file)
            },
            // 新增弹框
            handleAdd(){
              this.$refs.formDialogRef.add()
            },
            handleEdit(row){
              this.$refs.formDialogRef.edit(row)
            },
            reloadTable(){
              this.getList();
            }
        }
    };
</script>
